import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		loginProvider: "",
		openid: null,
		newComment: null,
		newTopic: null,
		needFreshPage: false,
		formId: [],
		selectedClub: null,
		selectedTechnician: null,
		newName: null,
		newAvatar: null,
		backToMyReferer: null,
		nowInLoginPage: false,
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setNewComment(state, newComment) {
			state.newComment = newComment
		},
		setNewTopic(state, newTopic) {
			state.newTopic = newTopic
		},
		setNeedFreshPage(state, value) {
			state.needFreshPage = value
		},
		setFormId(state, value) {
			state.formId = value
		},
		appendFormId(state, value) {
			let timestamp = parseInt((new Date).getTime() / 1000)
			let expiresAt = timestamp + 604800
			state.formId.push(value + "_" + expiresAt)
		},
		setSelectedClub(state, value) {
			state.selectedClub = value
		},
		setSelectedTechnician(state, value) {
			state.selectedTechnician = value
		},
		setNewName(state, value) {
			state.newName = value
		},
		setNewAvatar(state, value) {
			state.newAvatar = value
		},
		setBackToMyReferer(state, value) {
			state.backToMyReferer = value
		},
		setNowInLoginPage(state, value) {
			state.nowInLoginPage = value
		},
	},
	actions: {
		// lazy loading openid
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		}
	},
	getters: {
		getNewComment(state, getters) {
			return state.newComment
		},
		getNewTopic(state, getters) {
			return state.newTopic
		},
		getNeedFreshPage(state, getters) {
			return state.needFreshPage
		},
		getFormId(state, getters) {
			return state.formId
		},
		getSelectedClub(state, getters) {
			return state.selectedClub
		},
		getSelectedTechnician(state, getters) {
			return state.selectedTechnician
		},
		getNewName(state, getters) {
			return state.newName
		},
		getNewAvatar(state, getters) {
			return state.newAvatar
		},
		getBackToMyReferer(state, getters) {
			return state.backToMyReferer
		},
		getNowInLoginPage(state, getters) {
			return state.nowInLoginPage
		},
	}
})

export default store
